import os
import psutil

from django.shortcuts               import render, render_to_response, get_object_or_404
from django.http                    import HttpResponse, Http404, HttpResponseRedirect
from django.template                import RequestContext, loader
from django.views                   import generic
from django.core.urlresolvers       import reverse
from django.core.context_processors import csrf

import config.settings as settings

from print_request.models import Request
from print_request.forms  import UploadFileForm

import print_request.utils as utils

def review(request, id):
  context = {
    'request' : Request.objects.get(id=id),
    'response': '/'
  }
  context.update(csrf(request))
  return render_to_response('print_request/review.html', context)

def extension(request, ext):
  context = {
    'extension' : ext,
  }

  context['description'] = utils.get_extension_description(ext)

  return render_to_response('print_request/extension.html', context)

def import_file_query(request, form=UploadFileForm()):
  """
  Create the form to query a file upload.
  """
  context = {
    'upload_form' : form.as_p(),
    'title'       : 'Import file',
    'response'    : '/import_file/',
  }
  context.update(csrf(request))
  return render_to_response('print_request/import_file.html', context)

def import_file(request):
  """
  File query management.
  """
  # If something have benn posted.
  if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
      r = utils.handle_imported_file(
        request.FILES['file'],
        request.POST['title'],
        request.POST['short_description'],
        request.POST['description'])
      return HttpResponseRedirect('/' + str(r.id) + '/review/')
    # Else resend a query, displaying errors.
    else:
      return import_file_query(request, form)
  # Else query a post.
  else:
    return import_file_query(request)

def supported_format(request):
  ext_path = os.path.join(settings.BASE_DIR,
      'print_request', 'static', 'print_request', 'ext')
  extensions = sorted([ f for f in os.listdir(ext_path)
      if os.path.isfile(os.path.join(ext_path,f)) ])
  context = {
    'title'     : 'Supported Format',
    'extensions': extensions,
  }
  return render(request, 'print_request/supported_format.html', context)

def status(request):
  """
  Display printer status.
  """
  context = {
      'title': 'Status',
      'debug': 'true',
      'animation': 'true',
      'cpu_usage': psutil.cpu_percent(interval=1),
      'disk_usage': (int(1000*psutil.disk_usage('/').free/psutil.disk_usage('/').total)/10.0),
      'swap_usage': psutil.swap_memory().percent,
      'ram_usage': psutil.virtual_memory().percent,
      'laser_heat': 40,
      'processor_heat': 30,
      'internal_heat': 80,
      }
  return render(request, 'print_request/status.html', context)

def index(request):
  """
  Display history of uploads.
  """
  latest_requests = Request.objects.all().order_by('-pub_date')
  title = 'History'
  context = {
      'latest_requests': latest_requests,
      'title': title,
      }
  return render(request, 'print_request/index.html', context)

# vim:tabstop=2:softtabstop=2:shiftwidth=2
